<?php
namespace heihei\helpers;

/**
 * 树型结构操作类
 */
class TreeStructHelper {

  /**
   * 数组解析到树型格式
   * @param array $list 待处理的数组
   * @param array $config 处理配置
   * @return array
   */
  public static function toTree($list, $config = []){
    $config = array_merge([
      'parentKey' => 'parent_id',
      'childrensKey' => 'childrens',
      'parentValue' => null,
    ], $config);
    list('parentKey' => $parentKey, 'childrensKey' => $childrensKey, 'parentValue' => $parentValue) = $config;
    $treeAll = [];
    foreach($list as &$item){
      $currentParentValue = $item[$parentKey];
      if(empty($currentParentValue)){
        $treeAll[] = &$item;
        continue;
      }
      if(!isset($list[$currentParentValue])){
        continue;
      }
      $parentItem = &$list[$currentParentValue];
      if(!isset($parentItem[$childrensKey])){
        $parentItem[$childrensKey] = [];
      }

      $parentItem[$childrensKey][] = &$item;
    }
    if($parentValue){
      return isset($list[$parentValue]) && isset($list[$parentValue][$childrensKey]) ? $list[$parentValue][$childrensKey] : [];
    }
    return $treeAll;
  }
}